<?php

namespace Track\Controller;

use Plume\Core\Controller;
use Plume\Core\Service;
use Plume\Core\Dao;
use Utils\ExcelToArrary;

class ExcelController extends Controller{

    public function __construct($app) {
        parent::__construct($app, new Service($app, new Dao($app, 'track_user')));
    }

    private function checklogin(){
        $login = $this->provider('session')->getSessionValue('status');
        if(empty($login) || $login === false){
            header("location:/track/index/index");
        }
    }

    public function indexAction(){
    	$this->checklogin();
    	$msg = "准备导入";
    	$detail = "无";
		if (! empty ( $_FILES ['file_stu'] ['name'] )){
		    $tmp_file = $_FILES['file_stu']['tmp_name'];
		    $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
		    $file_type = $file_types [count ( $file_types ) - 1];
		    $msg = '';
		     /*判别是不是.xls文件，判别是不是excel文件*/
		     if (strtolower ( $file_type ) != "xlsx"){
		          $msg = '不是Excel文件，重新上传';
		     }
		    /*设置上传路径*/
		     $savePath = $this->plume('plume.root.path').'var/upload/excel/';
		    /*以时间来命名上传的文件*/
		    $str = date ( 'Ymdhis' ); 
		    $file_name = $str . "." . $file_type;
		    /*是否上传成功*/
		    if (!copy($tmp_file, $savePath.$file_name )) {
				$msg = '上传失败';
		    }
		    $res = ExcelToArrary::read($savePath.$file_name);
		    // var_dump($res);
		    // die;
		   	//日期 来源渠道   来源跟踪关键字  姓名 地区 QQ号 电话  邮箱 年会类型 公司名称 年会规模 阶段 备注 

	        $insertArr = array();
			foreach ( $res as $k => $v ) {
				if($k == 1)continue;
			   	$data['date'] = $v[0];
			   	$data['from'] = $v[1];
			   	$data['fromkey'] = $v[2];
			   	$data['name'] = $v[3];
			   	$data['area'] = $v[4];
			   	$data['qq'] = $v[5];
			   	$data['tel'] = $v[6];
			   	$data['mail'] = $v[7];
			   	$data['nhtype'] = $v[8];
			   	$data['comname'] = $v[9];
			   	$data['nhscope'] = $v[10];
			   	$data['step'] = $v[11];
			   	$data['note'] = $v[12];
			   	$insertArr[] = $data;
			}
			$result = $this->service->insertMulti($insertArr);
			if(!$result){
				$msg = "导入到数据库失败";
			}
			// var_dump($result);
			$detail = $this->provider('dataBase')->connect()->getLastError();
			$msg = "导入成功";
		}
		$fileName = $this->getParamValue('filename');
		if(!empty($fileName)){
			$data= array(array('a' => 'a1', 'b' => 'b1'),array('a' => 'a2', 'b' => 'b2'));
			$res=ExcelToArrary::push($data,$fileName);
		}
		return $this->result(array('msg' => $msg, 'detail' => $detail))->response();
    }

}
